import React, {useEffect, useState} from 'react'
import {Link, useLocation, useNavigate} from 'react-router-dom'
import {reqGetRentHouse} from '@/api'
import NavHeader from '@/components/NavHeader'
import NoHouse from '@/components/NoHouse'
import {House} from '@/types'
import HouseItem from '@/components/HouseItem'
import {Toast} from 'antd-mobile'
import './index.less'

const Rent = () => {
    // 出租房屋列表
    const [list, setList] = useState<House[]>([])
    const [isLoading, setIsLoading] = useState(true)
    const nav = useNavigate()
    const location = useLocation()

    useEffect(() => {
        getHouseList()
    }, [])

    // 获取已发布房源的列表数据
    const getHouseList = async () => {
        Toast.show({icon: 'loading', content: '加载中…'})
        const res = await reqGetRentHouse()

        if (res.status === 200) {
            setList(res.body)
        } else {
            nav('/login', {state: {from: location}})
        }
        Toast.clear()
        setIsLoading(false)
    }

    return (
        <div className='rent'>
            <NavHeader>房屋管理</NavHeader>
            {!isLoading && list.length <= 0 ? (
                <NoHouse>
                    您还没有房源，
                    <Link to='/rent/add' className='link'>
                        去发布房源
                    </Link>
                    吧~
                </NoHouse>
            ) : (
                <div className='houses'>
                    {list.map((item) => (
                        <HouseItem key={item.houseCode} onClick={() => nav(`/detail/${item.houseCode}`)} item={item} />
                    ))}
                </div>
            )}
        </div>
    )
}

export default Rent
